//package com.leetomlee123.communication.server;
//
//import com.alibaba.fastjson.JSON;
//import com.google.common.collect.Lists;
//import com.google.common.collect.Maps;
//import com.leetomlee123.communication.constant.MessageType;
//import com.leetomlee123.communication.entity.OnlineUser;
//import com.leetomlee123.communication.entity.WebRequest;
//import io.netty.channel.Channel;
//import io.netty.channel.ChannelHandlerContext;
//import io.netty.channel.SimpleChannelInboundHandler;
//import io.netty.channel.group.ChannelGroup;
//import io.netty.channel.group.DefaultChannelGroup;
//import io.netty.handler.codec.http.DefaultFullHttpResponse;
//import io.netty.handler.codec.http.FullHttpResponse;
//import io.netty.handler.codec.http.HttpResponseStatus;
//import io.netty.handler.codec.http.HttpVersion;
//import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
//import io.netty.util.concurrent.GlobalEventExecutor;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.stereotype.Component;
//import org.springframework.util.StringUtils;
//
//import javax.annotation.PostConstruct;
//import java.util.ArrayList;
//import java.util.Iterator;
//import java.util.Map;
//
//import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN;
//import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS;
//import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS;
//
//@Component
//public class TextWebSocketFrameHandler extends
//        SimpleChannelInboundHandler<TextWebSocketFrame> {
//    public static TextWebSocketFrameHandler handler;
//
//    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
//
//    @Autowired
//    private RedisTemplate redisTemplate;
//
//    @PostConstruct
//    public void init() {
//        handler = this;
//    }
//
//    @Override
//    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
//        super.channelRegistered(ctx);
//    }
//
//    @Override
//    protected void channelRead0(ChannelHandlerContext ctx,
//                                TextWebSocketFrame msg) throws Exception { // (1)
//        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
//        response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
//        response.headers().set(ACCESS_CONTROL_ALLOW_HEADERS, "Origin, X-Requested-With, Content-Type, Accept");
//        response.headers().set(ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT,DELETE");
//        ctx.write(response);
//        String sc = msg.text();
//        String sender = JSON.parseObject(sc).get("sender").toString();
//        Channel incoming = ctx.channel();
//        String id = incoming.id().asLongText();
//        handler.redisTemplate.opsForValue().set("olur_" + sender, id);
//        if (!StringUtils.isEmpty(JSON.parseObject(sc).get("content"))) {
//            if (Integer.valueOf(JSON.parseObject(sc).get("type").toString()) == 5) {
//                for (Channel channel : channels) {
//                    if (channel.id().asLongText().equals(JSON.parseObject(sc).get("id").toString())) {
//                        WebRequest webRequest = JSON.parseObject(sc, WebRequest.class);
//                        webRequest.setId(id);
//                        channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSON(webRequest).toString()));
//                    }
//                }
//            } else {
//                channels.writeAndFlush(new TextWebSocketFrame(sc));
//            }
//        } else {
//            onlineUsers();
//        }
//    }
//
//    private void onlineUsers() {
//        Iterator iterator = handler.redisTemplate.keys("olur_*").iterator();
//        ArrayList<OnlineUser> users = Lists.newArrayList();
//        while (iterator.hasNext()) {
//            String key = String.valueOf(iterator.next());
//            users.add(new OnlineUser(String.valueOf(handler.redisTemplate.opsForValue().get(key)), key.split("_")[1]));
//        }
//        WebRequest webRequest = new WebRequest(users, MessageType.USERS.getIndex());
//        channels.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(webRequest)));
//    }
//
//    @Override
//    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {  // (2)
//        Channel incoming = ctx.channel();
//        channels.add(incoming);
//        System.out.println("Client:" + incoming.remoteAddress() + "加入");
//    }
//
//    @Override
//    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {  // (3)
//        Channel incoming = ctx.channel();
//        Iterator iterator = handler.redisTemplate.keys("olur_*").iterator();
//        while (iterator.hasNext()) {
//            String key = String.valueOf(iterator.next());
//            if (String.valueOf(handler.redisTemplate.opsForValue().get(key)).equals(incoming.id().asLongText())) {
//                handler.redisTemplate.delete(key);
//
//            }
//        }
//        onlineUsers();
//        System.out.println("Client:" + incoming.remoteAddress() + "离开");
//
//    }
//
//    @Override
//    public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
//        Channel incoming = ctx.channel();
//        System.out.println("Client:" + incoming.remoteAddress() + "在线");
//    }
//
//    @Override
//    public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
//        Channel incoming = ctx.channel();
//        Iterator iterator = handler.redisTemplate.keys("olur_*").iterator();
//        while (iterator.hasNext()) {
//            String key = String.valueOf(iterator.next());
//            if (String.valueOf(handler.redisTemplate.opsForValue().get(key)).equals(incoming.id().asLongText())) {
//
//                handler.redisTemplate.delete(key);
//            }
//        }
//        onlineUsers();
//        System.out.println("Client:" + incoming.remoteAddress() + "掉线");
//    }
//
//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
//            throws Exception {
//        Channel incoming = ctx.channel();
//        Iterator iterator = handler.redisTemplate.keys("olur_*").iterator();
//        while (iterator.hasNext()) {
//            String key = String.valueOf(iterator.next());
//            if (String.valueOf(handler.redisTemplate.opsForValue().get(key)).equals(incoming.id().asLongText())) {
//
//                handler.redisTemplate.delete(key);
//            }
//        }
//        System.out.println(cause.getMessage());
//        System.out.println("Client:" + incoming.remoteAddress() + "异常");
//        ctx.close();
//    }
//
//}